#include "history.h"
#include <QDebug>

History::History(QObject *parent): QObject(parent),m_current(-1),m_maxSize(5)
{
    m_back = new QAction(QIcon(":/back"),tr("Назад"),this);
    connect(m_back,SIGNAL(triggered()),this,SLOT(goBack()));
    m_back->setEnabled(false);
    m_forward = new QAction(QIcon(":/forward"),tr("Вперед"),this);
    connect(m_forward,SIGNAL(triggered()),this,SLOT(goForward()));
    m_forward->setEnabled(false);
}
void History::setMaxSize(const int &maxSize)
{
    m_maxSize=maxSize;
    while(m_maxSize<=m_history.count())
    {
        DocEntity* item=m_history.takeFirst();
        item=0;
    }
}
QAction* History::back()
{
    return m_back;
}
QAction* History::forward()
{
    return m_forward;
}
void History::goBack()
{
    if(m_current>0)
    {
        m_current--;
        m_back->setEnabled(m_current!=0);
        m_forward->setEnabled(true);
        emit itemChange(m_history.at(m_current));
    }
}
void History::goForward()
{
    if(m_current<m_history.count()-1)
    {
        m_current++;
        m_forward->setEnabled(m_current!=m_history.count()-1);
        m_back->setEnabled(true);
        emit itemChange(m_history.at(m_current));
    }
}

void History::setCurrent(DocEntity *item)
{
    if(m_current>-1)
        if(item==m_history.at(m_current))
            return;
    if(m_history.count()==m_maxSize)
    {
        DocEntity* tmp=m_history.takeFirst();
        tmp=0;
    }
    if(m_forward->isEnabled())
        while(m_current!=m_history.count()-1)
        {
            DocEntity* tmp=m_history.takeLast();
            tmp=0;
        }
    m_current=m_history.count();
    m_history.append(item);
    m_forward->setEnabled(false);
    m_back->setEnabled(m_history.count()>1);
}
void History::clear()
{
    m_back->setEnabled(false);
    m_forward->setEnabled(false);
    foreach(DocEntity* item, m_history)item=0;
    m_history.clear();
}
